#!/usr/bin/python
#-*- coding: UTF-8 -*-
#  ___                _____         _             
# | __|_ _ ___ _ _   |_   _|  _ _ _| |____ _ _  _ 
# | _|| '_/ -_) ' \    | || || | '_| / / _` | || |  <turkay.eren@gmail.com>
# |___|_| \___|_||_|   |_| \_,_|_| |_\_\__,_|\_, |  // 2007-03-30
#                                            |__/ 
#
#-*- coding: UTF-8 -*-

import sys
import comar
import gettext
import veriables
from gettext import gettext as _
from util import List,UserInfo,GroupInfo
from window import UserEditWindow
from window import YesNoWindow
from window import AddUserWindow
from window import AddGroupWindow

try:
    import gtk
    import gtk.glade
except:
    print _("You have to install PyGTK 2.0 or later!")
    sys.exit(1)

gettext.bindtextdomain("user-manager", veriables.localedir)
gettext.textdomain("user-manager")
gtk.glade.bindtextdomain("user-manager", veriables.localedir)
gtk.glade.textdomain("user-manager")
gettext.install("user-manager")

class Main:
    def __init__(self):
        self.wTree = gtk.glade.XML("glade/main.glade", "mainWindow")

        # connect signals
        dict = {"destroy": gtk.main_quit,
                "about": self.show_about,
                "notebook_switch_page": self.notebook_switch_page_cb,
                "on_userview_cursor_changed": self.userview_cursor_changed,
                "on_groupview_cursor_changed": self.groupview_cursor_changed,
                "on_add_user_button_clicked": self.add_user,
                "on_edit_user_button_clicked": self.edit_user,
                "on_delete_group_button_clicked": self.delete_group,
                "on_add_group_button_clicked": self.add_group,
                "on_delete_user_button_clicked": self.delete_user,
                "on_system_users_groups_toggled": self.update_treeview_items}

        self.wTree.signal_autoconnect(dict)

        # hide group toolbar
        self.wTree.get_widget("group_tool_box").hide()

        # set edit, delete buttons unavailable 
        # it will be useable when user or grup is selected in treeView
        self.setUseable(False, "edit_user_button")
        self.setUseable(False, "delete_user_button")
        self.setUseable(False, "delete_group_button")

        # append user columns
        self.appendColumn("userview", _("Uid"), 0)
        self.appendColumn("userview", _("Name"), 1)
        self.appendColumn("userview", _("Real Name"), 2)
        # append group columns
        self.appendColumn("groupview", _("Gid"), 0)
        self.appendColumn("groupview", _("Name"), 1)

        self.userList = gtk.ListStore(str, str, str)
        self.groupList = gtk.ListStore(int, str)
        self.wTree.get_widget("userview").set_model(self.userList)
        self.wTree.get_widget("groupview").set_model(self.groupList)

        self.show_system_users = self.wTree.get_widget("system_users_groups").get_active()

    def appendColumn(self, name, title, id):
        column = gtk.TreeViewColumn(title, gtk.CellRendererText(), text=id)
        column.set_resizable(True)
        self.wTree.get_widget(name).append_column(column)

    def appendUsers(self, system=False):
        self.userList.clear()
        for user in List().getUsers():
            # the min value of uid is 1000 for users
            if not system:
                if user[0] >= 1000 and user[0] < 6534:
                    self.userList.append(user)
            else:
                self.userList.append(user)

    def appendGroups(self, system=False):
        self.groupList.clear()
        for group in List().getGroups():
            if not system:
                if group[0] >= 1000 and group[0] < 6533:
                    self.groupList.append(group)
            else:
                self.groupList.append(group)

    def setUseable(self, value, *args, **kwargs):
        for widget in args:
            self.wTree.get_widget(widget).set_sensitive(value)

    def loop(self):
        try:
            self.appendUsers()
            self.appendGroups()

            self.wTree.get_widget("mainWindow").show()
            gtk.main()
        except comar.CannotConnect:
            self.setUseable(False, "groupview", "userview", "user_tool_box", "group_tool_box", "notebook", "options_menu")
            self.wTree.get_widget("mainWindow").show()

            error = gtk.glade.XML("glade/main.glade", "error")
            dialog = error.get_widget("error")
            dialog.set_markup(_('<b>Can not connect to COMAR!</b>'))
            dialog.format_secondary_markup(_('Please start COMAR first by "service comar start" with root privileges'))
            dialog.run()
            dialog.destroy()

            gtk.main()


# ==============================================
#                SIGNALS
# ==============================================

    def notebook_switch_page_cb(self, widget, pointer, number):
        # if group is selected, show group menus
        if number == 1:
            self.wTree.get_widget("user_tool_box").hide()
            self.wTree.get_widget("group_tool_box").show()
        # else show user toolbar
        else:
            self.wTree.get_widget("user_tool_box").show()
            self.wTree.get_widget("group_tool_box").hide()

    def userview_cursor_changed(self, widget):
        self.setUseable(True, "edit_user_button")
        self.setUseable(True, "delete_user_button")

    def groupview_cursor_changed(self, widget):
        self.setUseable(True, "delete_group_button")

    def update_treeview_items(self, widget):
        if widget.get_active():
            self.appendUsers(True)
            self.appendGroups(True)
        else:
            self.appendUsers()
            self.appendGroups()

    def show_about(self, widget):
        about = gtk.glade.XML("glade/main.glade", "about")
        about.get_widget("about").run()
        about.get_widget("about").destroy()        

    def edit_user(self, widget, path="", column=""):
        (store,iter) = self.wTree.get_widget("userview").get_selection().get_selected()
        uid = store.get_value(iter, 0)

        UserEditWindow(uid, self).show()

    def add_user(self, widget):
        AddUserWindow(self).show()

    def delete_user(self, widget):
        (store,iter) = self.wTree.get_widget("userview").get_selection().get_selected()
        uid = store.get_value(iter, 0)
        user = UserInfo(uid).name    

        yesno = YesNoWindow("Delete User", _('Do you really want to delete user <b>%s</b>?') % user)
        response = yesno.run()
        yesno.destroy()
        if response == -8:
             link = comar.Link()
             link.call("User.Manager.deleteUser", {"uid": uid})

             print "DEBUG [deleteuser]: %s" % link.read_cmd()

             self.appendUsers(self.show_system_users)
             self.wTree.get_widget("statusbar").push(0, _('User "%s" deleted') % user)

    def delete_group(self, widget):
        (store,iter) = self.wTree.get_widget("groupview").get_selection().get_selected()
        gid = store.get_value(iter, 0)
        groupname = GroupInfo(gid).name

        yesno = YesNoWindow("Delete Group", _("Do you really want to delete group <b>%s</b>?") % groupname)
        response = yesno.run()
        yesno.destroy()
        if response == -8:
            link = comar.Link()
            link.call("User.Manager.deleteGroup", {"gid": gid})

            print "DEBUG [deletegroup]: %s" % link.read_cmd()

            self.appendGroups(self.show_system_users)
            self.wTree.get_widget("statusbar").push(0, _('Group "%s" deleted') % groupname)

    def add_group(self, widget):
        AddGroupWindow(self).show()


window = Main()
window.loop()
